// token验证模块
const JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose')

const User = mongoose.model('Users')
const keys = require('../config/keys')

// opts 配置信息
const opts = {}
//用配置信息 调用jwt的请求验证token
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;

module.exports = passport => {
    // passport根据 token去验证的      
    // 值: 1 jwt_payload验证返回的数据   2 done回调函数
    passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
        //根据Id查询
        User.findById(jwt_payload.id)
        .then(user => {
            //查不到就返回false  查到了就返回用户信息
            if(!user){
                return done(null,false)
            }else{
                return done(null,user)
            }
        })
        .catch(err => console.log(err))
    }));

}